<template>
  <el-card class="full-card">
    <h2 class="page-title">公告管理</h2>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" label-width="100px" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="标题">
            <el-input v-model.trim="queryParams.title" placeholder="请输入标题" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option label="已发布" :value="1" />
              <el-option label="草稿" :value="0" />
              <el-option label="已下架" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
            <el-button type="success" @click="toggleDrawer('create')">新建公告</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe style="width: 100%; margin: 20px 0">
      <el-table-column prop="title" label="标题" min-width="200px" />
      <el-table-column prop="category" label="分类" min-width="120px" />
      <el-table-column prop="author" label="发布人" min-width="100px" />
      <el-table-column prop="publishTime" label="发布时间" min-width="160px" :formatter="formatDate" />
      <el-table-column prop="status" label="状态" min-width="100px">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '已发布' : row.status === 0 ? '草稿' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180px">
        <template #default="{ row }">
          <el-button @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="queryParams.currentPage"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="fetchData"
        class="pagination"
    />

    <!-- 编辑抽屉 -->
    <el-drawer
        v-model="isDrawerOpen"
        :title="drawerTitle"
        direction="rtl"
        size="60%"
        @close="resetForm"
    >
      <el-form :model="formData" label-width="120px">
        <el-form-item label="标题" required>
          <el-input v-model.trim="formData.title" placeholder="请输入公告标题" />
        </el-form-item>

        <el-form-item label="分类" required>
          <el-select v-model="formData.category" placeholder="请选择分类">
            <el-option label="系统公告" value="系统公告" />
            <el-option label="活动通知" value="活动通知" />
            <el-option label="更新日志" value="更新日志" />
          </el-select>
        </el-form-item>

        <el-form-item label="是否置顶">
          <el-switch v-model="formData.isTop" :active-value="1" :inactive-value="0" />
        </el-form-item>

        <el-form-item label="是否紧急">
          <el-switch v-model="formData.isUrgent" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="公告状态" required>
          <el-select v-model="formData.status" placeholder="请选择公告状态">
            <el-option label="草稿" :value="0" />
            <el-option label="已发布" :value="1" />
            <el-option label="已下架" :value="2" />
          </el-select>
        </el-form-item>

        <!-- 富文本编辑器 -->
        <el-form-item label="内容" required>
          <div ref="editorContainer" class="editor-container"></div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="toggleDrawer()">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-drawer>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue";
import E from "wangeditor"; // 确保路径正确
import adminApi from "../../apis/adminAPi.js";
import { ElMessage } from "element-plus";

const queryParams = ref({
  currentPage: 1,
  pageSize: 10,
  title: "",
  status: null,
});

const tableData = ref([]);
const total = ref(0);

// 编辑抽屉状态
const isDrawerOpen = ref(false);
const drawerTitle = ref("");
const formData = ref({
  id: null,
  title: "",
  category: "系统公告",
  content: "",
  isTop: 0,
  isUrgent: 0,
  status: 0, // 默认为草稿状态
});

// 富文本编辑器相关
const editorContainer = ref(null);
let editorInstance = null;

// 初始化列表
const fetchData = async () => {
  try {
    const res = await adminApi.getAnnouncementList({
      currentPage: queryParams.value.currentPage,
      pageSize: queryParams.value.pageSize,
      title: queryParams.value.title,
      status: queryParams.value.status,
    });
    if (res.code === 200) {
      tableData.value = res.data.records;
      total.value = res.data.total;
    }
  } catch (error) {
    ElMessage.error("数据加载失败");
  }
};

// 搜索
const handleSearch = () => {
  queryParams.value.currentPage = 1;
  fetchData();
};

// 重置搜索
const resetQuery = () => {
  queryParams.value = {
    currentPage: 1,
    pageSize: 10,
    title: "",
    status: null,
  };
  fetchData();
};

// 格式化时间
const formatDate = (row, column, cellValue) => {
  return new Date(cellValue).toLocaleString();
};

// 抽屉控制
const toggleDrawer = (type = "create", row = null) => {
  isDrawerOpen.value = !isDrawerOpen.value;
  drawerTitle.value = type === "create" ? "新建公告" : "编辑公告";
  if (row && type === "edit") {
    loadAnnouncementDetail(row.id);
  } else {
    resetForm();
  }

  // 抽屉打开后初始化编辑器
  nextTick(() => {
    if (isDrawerOpen.value && editorContainer.value) {
      initEditor();
    }
  });
};

// 加载公告详情（编辑时）
const loadAnnouncementDetail = async (id) => {
  try {
    const res = await adminApi.getAnnouncementDetail(id);
    if (res.code === 200) {
      formData.value = {
        id: res.data.id,
        title: res.data.title,
        category: res.data.category,
        content: res.data.content,
        isTop: res.data.isTop,
        isUrgent: res.data.isUrgent,
        status: res.data.status,
      };
      // 确保编辑器已初始化
      if (editorInstance) {
        editorInstance.txt.html(res.data.content);
      }
    }
  } catch (error) {
    ElMessage.error("加载公告详情失败");
  }
};

// 重置表单
const resetForm = () => {
  formData.value = {
    id: null,
    title: "",
    category: "系统公告",
    content: "",
    isTop: 0,
    isUrgent: 0,
    status: 0,
  };
  // 清空编辑器内容
  if (editorInstance) {
    editorInstance.txt.clear();
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formData.value.title) {
    ElMessage.warning("标题不能为空");
    return;
  }
  if (!formData.value.content) {
    ElMessage.warning("内容不能为空");
    return;
  }

  try {
    const apiMethod = formData.value.id
        ? adminApi.updateAnnouncement
        : adminApi.createAnnouncement;
    const res = await apiMethod(formData.value);
    if (res.code === 200) {
      ElMessage.success("操作成功");
      toggleDrawer();
      fetchData();
    }
  } catch (error) {
    ElMessage.error("操作失败");
  }
};

// 编辑按钮点击
const handleEdit = (row) => {
  toggleDrawer("edit", row);
};

// 删除按钮点击
const handleDelete = async (row) => {
  try {
    await adminApi.deleteAnnouncement(row.id);
    ElMessage.success("删除成功");
    fetchData();
  } catch (error) {
    ElMessage.error("删除失败");
  }
};

// 分页处理
const handleSizeChange = (size) => {
  queryParams.value.pageSize = size;
  fetchData();
};

// 初始化编辑器（确保在 DOM 渲染后执行）
const initEditor = () => {
  if (!editorInstance && editorContainer.value) {
    editorInstance = new E(editorContainer.value);
    editorInstance.config.height = 500;
    editorInstance.config.zIndex = 1;
    editorInstance.config.uploadImgServer = "http://localhost:88/File/upImg"; // 替换为实际上传地址
    editorInstance.config.withCredentials = true;
    editorInstance.config.uploadFileName = "file";
    editorInstance.config.uploadImgHooks = {
      customInsert: (insertImg, result) => {
        console.log("返回的结果是", result); // 打印返回数据用于调试
        // 校验返回数据
        if (!result || !result.data) {
          console.error("图片上传失败：返回数据格式不正确", result);
          ElMessage.error("图片上传失败，请稍后重试");
          return;
        }
        const url = result.data; // 直接使用 result.data 作为图片 URL
        insertImg(url);
      },
    };
    editorInstance.config.onchange = (newHtml) => {
      formData.value.content = newHtml;
    };
    editorInstance.create();
  }
};

// 销毁编辑器
const destroyEditor = () => {
  if (editorInstance) {
    editorInstance.destroy();
    editorInstance = null;
  }
};

// 生命周期钩子
onMounted(async () => {
  await fetchData();
});

// 组件卸载前销毁编辑器
onBeforeUnmount(() => {
  destroyEditor();
});
</script>

<style scoped>
.editor-container {
  margin-bottom: 20px;
  height: 500px; /* 确保容器有高度 */
}

.full-card {
  margin: 20px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.search-form :deep(.el-form-item__content) {
  width: 100%;
}

.pagination {
  text-align: right;
  margin-top: 20px;
}
</style>
